<template>
  <div class="app-container" v-loading="pageLoading">
    <el-form :rules="rules"
             label-position="top"
             ref="saveForm"
             label-width="80px"
             :model="saveForm">

      <el-form-item label="订单编号" v-if="saveForm.orderno">
        <el-input v-model="saveForm.orderno" disabled></el-input>
      </el-form-item>
      <el-form-item label="货物名称（Cargo name）" prop="goodsName">
        <el-input v-model="saveForm.goodsName" placeholder="请输入货物名称（Please enter Cargo name）"></el-input>
      </el-form-item>
      <el-form-item label="货物体积（Volume of goods）">
        <el-input v-model="saveForm.goodsSize"
                  oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
                  placeholder="请输入货物体积（Please enter Volume of goods）"></el-input>
      </el-form-item>
      <el-form-item label="包装数量（Number of packages of goods）">
        <el-input v-model="saveForm.packageNum"
                  placeholder="请输入包装数量（Please enter Number of packages of goods）"
                  oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"></el-input>
      </el-form-item>
      <el-form-item label="货物总数（Total number of cargoes）">
        <el-input v-model="saveForm.total"
                  placeholder="请输入货物总数（Please enter Total number of cargoes）"
                  oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"></el-input>
      </el-form-item>
      <el-form-item label="存放区号（Storage area number）" prop="area">
        <el-input v-model="saveForm.area" placeholder="请输入货物存放区号（Please enter Cargo Storage area number）"></el-input>
      </el-form-item>
      <el-form-item label="入仓日期（Please select Date of entry into warehouse）" prop="warehousingTime">
        <el-date-picker
          :editable="false"
          v-model="saveForm.warehousingTime"
          value-format="yyyy-MM-dd HH:mm"
          type="datetime"
          placeholder="请选择入仓时间（Please select Date of entry into warehouse）">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="客户姓名（Customer's name）" prop="customerName">
        <el-input v-model="saveForm.customerName" placeholder="请输入客户姓名（Please enter Customer's name）" @blur="selectCustomerInfo"></el-input>
      </el-form-item>
      <el-form-item label="客户代码（Customer's code）" prop="customerCode" v-if="saveForm.customerCode != ''">
        <el-input v-model="saveForm.customerCode" disabled></el-input>
      </el-form-item>
      <el-form-item label="客户电话（Customer's phone number）" prop="customerPhone">
        <el-input v-model="saveForm.customerPhone"
                  placeholder="请输入客户电话（Please enter Customer's phone number）"
                  :disabled="saveForm.customerId == '' ? false : true"></el-input>
      </el-form-item>
      <el-form-item label="客户国籍（Customer's nationality）" prop="nationalityInfo">
        <el-input v-if="saveForm.customerId != ''" v-model="saveForm.nationalityName" disabled></el-input>
        <el-select v-model="saveForm.nationalityInfo"
                   v-if="saveForm.customerId == ''"
                   placeholder="请选择客户国籍（Please select customer nationality）"
                   value-key="code"
                   @change="changeNationality">
          <el-option v-for="item in nationalityList"
                     :label="item.text"
                     :value="item"
                     :key="item.code"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="档口地址（Stall address）" prop="sellerAddress">
        <el-input v-model="saveForm.sellerAddress" placeholder="请输入档口地址（Please enter Stall address）"></el-input>
      </el-form-item>
      <el-form-item label="档口电话（Stall phone）" prop="sellerPhone">
        <el-input v-model="saveForm.sellerPhone" placeholder="请输入档口电话（Please enter Stall phone）"></el-input>
      </el-form-item>

      <!-- 物流公司、公司电话、公司地址 -->
      <el-row :gutter="20">
        <el-col :span="!saveForm.companyId ? 24 : 8" :xs="24">
          <el-form-item label="物流公司（Logistics company）" prop="company">
            <el-select v-model="saveForm.company"
                       placeholder="请选择物流公司（Please select a logistics company）"
                       value-key="id"
                       @change="changeCompany">
              <el-option v-for="item in companyList"
                         :label="item.cname"
                         :value="item"
                         :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="saveForm.companyId" :span="8" :xs="24">
          <el-form-item label="公司电话（Logistics company phone）" prop="companyPhone">
            <el-input v-model="saveForm.companyPhone" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col v-if="saveForm.companyId" :span="8" :xs="24">
          <el-form-item label="公司地址（Logistics company address）" prop="companyAddress">
            <el-input v-model="saveForm.companyAddress" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item style="width: 100%;display: flex;justify-content: center">
        <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { findCompanyList, getCustomerInfo, countryList } from '@/api/system/common'
import { addOrder } from '@/api/system/order'
import {parseTime} from "@/utils/ruoyi";

export default {
  name: "save-order",
  data() {
    return {
      pageLoading: false,
      companyList: [],
      nationalityList: [],
      saveForm: {
        orderno: '',
        goodsName: '',
        goodsSize: '',
        packageNum: '',
        total: '',
        area: '',
        warehousingTime: new Date(),
        customerId: '',
        customerName: '',
        customerCode: '',
        customerPhone: '',
        nationalityInfo: '',
        nationality: '',
        nationalityName: '',
        sellerAddress: '',
        sellerPhone: '',
        company: '',
        companyId: '',
        companyPhone: '',
        companyAddress: ''
      },
      rules: {
        goodsName: [
          {required: true, message: '货物名称不能为空（Cargo name cannot be empty）', trigger: 'blur'}
        ],
        area: [
          {required: true, message: '存放区号不能为空（Storage area number cannot be empty）', trigger: 'blur'}
        ],
        warehousingTime: [
          {required: true, message: '请选择入仓时间（Please select Date of entry into warehouse）', trigger: 'blur'}
        ],
        customerName: [
          {required: true, message: '客户姓名不能为空（Customer\'s name cannot be empty）', trigger: 'blur'}
        ],
        customerPhone: [
          {required: true, message: '客户电话不能为空（Customer\'s cannot be empty）', trigger: 'blur'}
        ],
        sellerAddress: [
          {required: true, message: '档口地址不能为空（Stall address cannot be empty）', trigger: 'blur'}
        ],
        sellerPhone: [
          {required: true, message: '档口电话不能为空（Stall phone cannot be empty）', trigger: 'blur'}
        ],
        company: [
          {required: true, message: '请选择物流公司（Please select a logistics company）', trigger: 'change'}
        ],
      }
    }
  },
  async created() {
    try {
      this.pageLoading = true;
      await this.getCompanyList();
      await this.getCountryList();
      this.pageLoading = false;
    }catch (e) {
      this.pageLoading = false;
    }
  },
  methods: {
    // 获取国籍列表
    async getCountryList() {
      this.nationalityList = (await countryList()).data;
    },
    // 获取公司列表
    async getCompanyList() {
      this.companyList = (await findCompanyList()).data;
    },
    // 切换公司
    changeCompany(val) {
      this.saveForm.companyId = val.id;
      this.saveForm.companyAddress = val.address;
      this.saveForm.companyPhone = val.phone;
    },
    // 国籍切换
    changeNationality(val) {
      this.saveForm.nationality = val.code;
      this.saveForm.nationalityName = val.text;
    },
    // 获取客户详情
    async selectCustomerInfo() {
      if (this.saveForm.customerName.trim()) {
        const {data} = await getCustomerInfo(this.saveForm.customerName);
        this.saveForm.nationalityName = data.nationalityName;
        this.saveForm.nationality = data.nationalityId;
        this.saveForm.customerCode = data.code;
        this.saveForm.customerPhone = data.phone;
        this.saveForm.customerId = data.userId != null ? (data.userId + '') : '';
        console.log(this.saveForm);
      }
    },
    submitForm() {
      this.$refs["saveForm"].validate((valid) => {
        if (valid) {
          this.pageLoading = true;
          this.saveForm.warehousingTime = this.parseTime(this.saveForm.warehousingTime)
          addOrder(this.saveForm).then((res) => {
            this.$message.success("添加成功");
            this.saveForm.orderno = res.data.orderno;
            this.resetForm();
            this.pageLoading = false;
          }).catch((e) => {
            this.pageLoading = false;
          })
        }
      });
    },
    resetForm() {
      this.saveForm = {
        orderno: '',
        goodsName: '',
        goodsSize: '',
        packageNum: '',
        total: '',
        area: '',
        warehousingTime: '',
        customerId: '',
        customerName: '',
        customerCode: '',
        customerPhone: '',
        nationalityInfo: '',
        nationality: '',
        nationalityName: '',
        sellerAddress: '',
        sellerPhone: '',
        company: '',
        companyId: '',
        companyPhone: '',
        companyAddress: ''
      }
      this.$refs["saveForm"].resetFields();
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {

  ::v-deep .el-form-item {
    margin-bottom: 22px !important;
  }

  ::v-deep .el-form-item--medium .el-form-item__label {
    line-height: 16px !important;
  }

  ::v-deep .el-select {
    width: 100%;
  }
  ::v-deep .el-date-editor {
    width: 100%;
  }
}
</style>
